package repository

import (
	"context"
	"demo/domain/model"
	"demo/domain/model/vo"
	"errors"
	"gorm.io/gorm"
	"time"
)

type visitStatisticsRepository struct {
	db *gorm.DB
}

func (v visitStatisticsRepository) SelectByUniqueKey(ctx context.Context, statisticsDate time.Time, compressCode string,
	shortUrlDigest string, longUrlDigest string) (*model.VisitStatistics, error) {
	var entity model.VisitStatistics
	err := v.db.WithContext(ctx).First(&entity, "statistics_date=? and compress_code=? and short_url_digest=? and long_url_digest=?",
		statisticsDate, compressCode, shortUrlDigest, longUrlDigest).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 确实没有数据
			return nil, nil
		}
		// 其他错误（如数据库连接问题）
		return nil, err
	}
	return &entity, err
}

func (v visitStatisticsRepository) Update(ctx context.Context, entity *model.VisitStatistics) error {
	return v.db.WithContext(ctx).Model(entity).Select("pv_count", "uv_count", "ip_count",
		"effective_redirection_count", "ineffective_redirection_count").Updates(entity).Error
}

func (v visitStatisticsRepository) StatisticsByCondition(ctx context.Context, query *vo.ShortUrlStatisticsCondition) ([]vo.ShortUrlStatisticsResult, int64, error) {
	tx := v.db.WithContext(ctx).Model(&vo.ShortUrlStatisticsResult{}).
		Where("compress_code = ?", query.CompressCode)
	// 动态条件
	if query.StartStatisticsDate != "" {
		tx = tx.Where("statistics_date >= ?", query.StartStatisticsDate)
	}
	if query.EndStatisticsDate != "" {
		tx = tx.Where("statistics_date <= ?", query.EndStatisticsDate)
	}
	// 统计总数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	// 查询领域实体列表
	var entities []vo.ShortUrlStatisticsResult
	offset := (query.PageNum - 1) * query.PageSize
	if err := tx.
		Order("id DESC").
		Limit(query.PageSize).
		Offset(offset).
		Find(&entities).Error; err != nil {
		return nil, 0, err
	}
	// 直接返回领域实体，不做DTO转换
	return entities, total, nil
}

func (v visitStatisticsRepository) Save(ctx context.Context, entity *model.VisitStatistics) error {
	return v.db.WithContext(ctx).Create(entity).Error
}

// NewVisitStatisticsRepository 创建一个新的 Repository 实例
func NewVisitStatisticsRepository(db *gorm.DB) model.VisitStatisticsRepository {
	return &visitStatisticsRepository{db: db}
}
